<template>
  <main>
    <Hero v-if="featured" :item="featured" />
    <ListingCarousel
      v-if="trendingMovies && trendingMovies.length"
      :title="trendingMoviesTitle"
      :view-all-url="trendingMoviesUrl"
      :items="trendingMovies" />

    <ListingCarousel
      v-if="trendingTvShows && trendingTvShows.length"
      :title="trendingTvTitle"
      :view-all-url="trendingTvUrl"
      :items="trendingTvShows" />
  </main>
</template>
<script setup>
import { ref } from "vue";
import { getTrending, getMovie, getTvShow, getListItem } from "@/api";
import Hero from "@/components/Hero.vue";
import ListingCarousel from "@/components/ListingCarousel.vue";

const trendingMovies = ref([]);
const trendingTvShows = ref([]);
const featured = ref(null);

const trendingMoviesTitle = getListItem("movie", "trending").title;

const trendingTvTitle = getListItem("tv", "trending").title;

const trendingMoviesUrl = {
  name: "movieCategory",
  params: { name: "trending" },
};

const trendingTvUrl = {
  name: "tvCategory",
  params: { name: "trending" },
};

Promise.all([getTrending("movie"), getTrending("tv")]).then(
  ([movies, tvShows]) => {
    trendingMovies.value = movies.results;
    trendingTvShows.value = tvShows.results;

    const trendings = [...movies.results, ...tvShows.results];
    const randomTrending =
      trendings[Math.floor(Math.random() * trendings.length)];
    const media = randomTrending.title ? "movie" : "tv";

    if (media === "movie") {
      getMovie(randomTrending.id).then((movie) => {
        featured.value = movie;
      });
    } else {
      getTvShow(randomTrending.id).then((tvShow) => {
        featured.value = tvShow;
      });
    }
  }
);
</script>
